var restClock;
var nForThisHour = 0;
var countdownStartTime;
 var countInterval = 5 * 60; //计数时间间隔
//var countInterval = 3; //计数时间间隔

// 月： month；
// 日： date;
// 星期: day;
// 年月日：ymd;
function numberToDay(number) {
    var day = "";
    switch (number) {
        case 0:
            day = "周日";
            break;
        case 1:
            day = "周一";
            break;
        case 2:
            day = "周二";
            break;
        case 3:
            day = "周三";
            break;
        case 4:
            day = "周四";
            break;
        case 5:
            day = "周五";
            break;
        case 6:
            day = "周六";
            break;
    }
    return day;
}

function updateChartData(localCounter) {
    var chartData = {
        days: [],
        numbers: [],
        ymds:[]
    };
    for (var i = 0; i < 7; i++) {
        if (localCounter[i]) {
            // for (var x in localCounter[i]) {
            //     console.log(x)
                chartData.days.unshift(numberToDay(parseInt(localCounter[i].day)));
                chartData.numbers.unshift(localCounter[i].effectCounter);
                chartData.ymds.unshift(localCounter[i].ymd);
            // }
        } else {
            chartData.days.unshift("");
            chartData.numbers.unshift(0);
            chartData.ymds.unshift(null);
        }
    }
    // console.log(chartData)
    return chartData;
}

function timeToClock(now) {
    var year = now.getFullYear();
    var tempMonth = now.getMonth() + 1;
    var month = (tempMonth + "").length === 1 ? "0" + tempMonth : tempMonth;
    var tempDate = now.getDate();
    var date = (tempDate + "").length === 1 ? "0" + tempDate : tempDate;
    var hour = now.getHours();
    var tempMin = now.getMinutes();
    var min = (tempMin + "").length === 1 ? "0" + tempMin : tempMin;
    var tempSec = now.getSeconds();
    var sec = (tempSec + "").length === 1 ? "0" + tempSec : tempSec;
    this.ymd = "" + year + month + date;
    this.time = "" + hour + min + sec;
    this.day = "" + now.getDay();
    // console.log(this.today + this.time);
    return this;
}

function displayNowClock() {
    setInterval(function () {
        var nowClock = timeToClock(new Date()).time;
        var displayTime = nowClock.slice(0, 2) + ":" + nowClock.slice(2, 4) + ":" + nowClock.slice(4, 6);
        $(".nowClock>p").text(displayTime)

    }, 1000);
}

function displayRestTime(restM, restS) {

    clearInterval(restClock);
    console.log("计数器清零");
    restClock = setInterval(function () {
        if (restS === "00") {
            restM--;
            restS = 60
        }
        restS--;
        if (restM === -1) {
            clearInterval(restClock);
            $(".start").click();
        }
        // console.log("restClock", restClock);
        restM = (restM + "").length === 1 ? "0" + restM : restM;
        restS = (restS + "").length === 1 ? "0" + restS : restS;
        var displayTime = "00:" + restM + ":" + restS;
        $(".restClock>p").text(displayTime);

    }, 1000);
}

function updateRestTime() {
    var restSeconds = 3600 - Math.round(((new Date()).getTime() - countdownStartTime.getTime()) / 1000);
    var restM = Math.floor(restSeconds / 60);
    var restS = restSeconds % 60;
    displayRestTime(restM, restS);
    console.log(restSeconds, restM, restS);
}

//入口
$(function () {

    //显示当前时钟
    displayNowClock();

    var localCounter = [];
    if (localStorage.counter) {
        localCounter = JSON.parse(localStorage.counter);
        // console.log("localCounter", localCounter)
    }

    var chartData = updateChartData(localCounter);

    //统计图表

    console.log("localCounter", localCounter);
    console.log("chartData", chartData);
    var chartBar = echarts.init(document.getElementById('chartBar'));
    var option = {
        title: {
            text: '最近一周计数',
            left: "center"
        },
        color: ['#3398DB'],
        /*tooltip: {
            // trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            },
            show: true,
            formatter: function (params) {
                var value = params.value;
                return params.name + "：" + value + "(" + value * 12 + ")\n"+chartData.ymds;

            }
        },*/
        grid: {
            left: '3%',
            right: '4%',
            top: "15%",
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: chartData.days,
/*                data: function () {
                    var temp =[];
                    for(var i=0;i<chartData.days.length;i++){
                        temp[i]=chartData.dates[i]+chartData.days[i]
                    }
                    alert(temp)
                    console.log("temp",temp)
                    return temp;
                },*/
                axisTick: {
                    alignWithLabel: true
                }
            }
        ],
        yAxis: [
            {
                name: "实际计数(今天总数)",
                type: 'value',
                minInterval: 1, //保证坐标轴分割刻度显示成整数。
                axisLabel: {
                    formatter: function (value) {
                        return value + "(" + value * 12 + ")"
                    }
                }
            }
        ],
        tooltip:{},
        series: [
            {
                name: '胎动次数',
                type: 'bar',
                barWidth: '60%',
                tooltip: {
                    // trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    show: true,
//                    formatter: '{b0}: {c0}<br />{b1}: {c1}',
                    formatter: function (params) {
//                    console.log(params)
                        var value = params.value;
                        return params.name + "：" + value + "(" + value * 12 + ")<br>"+chartData.ymds[params.dataIndex];
//                        return params.name + "：" + value + "(" + value * 12 + ")";

                    }
                },
                data: chartData.numbers
            }
        ]
    };
    chartBar.setOption(option, true);

    //计数器开关
    $(".start").click(function (e) {
        if ($(".start ~ :checked").length) {
            $(".counting").removeClass("disabled");
            $(this).children("span").text("关闭计数器");
            $(".updateRestTime").removeAttr("disabled");
            displayRestTime(59, 59);//倒计时显示
            nForThisHour = 0;
            // localCounter[0][today].effectCounter = 0;
            countdownStartTime = new Date();
        } else {
            $(".counting").addClass("disabled");
            $(this).children("span").text("开启计数器");
            $(".updateRestTime").attr("disabled", "false");
            clearInterval(restClock);
            console.log("计数器清零");
            alert("计数结束！")

        }
    });


    //更新剩余时间
    $(".updateRestTime").click(function () {
        updateRestTime();
    });
    //计数动作
    var prevTime = 0;
    $(".counting").click(function () {//点击计数

        // chartBar.dispose();
        chartBar = echarts.init(document.getElementById('chartBar'));
        var now = new Date();
        var obj = timeToClock(now);
        var ymd = obj.ymd;
        var time = obj.time;
        var day = obj.day;
        console.log(ymd+" "+time)

        if ((prevTime === 0) || (now - prevTime > countInterval * 1000)) {
            prevTime = now;
            nForThisHour++;//本次计数
            $(".counterNum").text(nForThisHour);
            $(".estimateNum").text(nForThisHour * 12);

            if (localCounter[0] && (localCounter[0].ymd===ymd)) {
                // localCounter[0].ymd = ymd;
                localCounter[0].data.push(time);
                localCounter[0].effectCounter = nForThisHour;
            } else {
                var objToday = {};
                objToday = {
                    ymd:ymd,
                    data: [time],
                    day: day,
                    effectCounter: nForThisHour
                };
                localCounter.unshift(objToday)
            }


            localStorage.counter = JSON.stringify(localCounter);
            chartData = updateChartData(JSON.parse(localStorage.counter));
            // console.log("chartData.days", chartData.days);
            //下面的两个中括号漏了就坑死人了！
            option.xAxis[0].data = chartData.days;
            option.series[0].data = chartData.numbers;


            // console.log("localCounter", localCounter);
            // console.log(JSON.parse(localStorage.counter))
            prevTime = now;
        } else {
            var displayTime = timeToClock(prevTime).time.slice(0, 2) + ":" + timeToClock(prevTime).time.slice(2, 4) + ":" + timeToClock(prevTime).time.slice(4, 6)
            alert("计数无效！距离上次计数时间" + displayTime + "还不到5分钟");
            prevTime = now;
            return;
        }

        chartBar.clear();
        // console.log("option", option);
        chartBar.setOption(option, true);

    })

});





